package org.crag.cafca.gui.servlet;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.SortedSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.crag.cafca.db.SqlConnector;
import org.crag.cafca.logic.time.Event;
import org.crag.cafca.logic.time.SourceEvent;
import org.crag.cafca.logic.time.TimeLine;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Servlet used for retrieving traveled kilometers
 * ATTENTION : For the moment, only for the BMW. 
 * @author Celien
 *
 */
@WebServlet("/OdometerServlet")
public class OdometerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
   
    public OdometerServlet() 
    {
        super();    
    }

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		HttpSession session = request.getSession(); 
		TimeLine timeline = (TimeLine) session.getAttribute("timeline"); 
		JSONObject json = createJSON(timeline); 
		response.getWriter().print(json.toString());
		response.setStatus(HttpServletResponse.SC_OK);
	}
	
	private JSONObject createJSON(TimeLine timeline)
	{
		JSONObject result = new JSONObject(); 
		JSONArray dataArray = new JSONArray(); 
		SortedSet<Event> events = timeline.getEvents(); 
		
		for(Event event : events)
		{
			if(!(event instanceof SourceEvent))
				continue;
			
			SourceEvent sourceEvent = (SourceEvent)event;
			
			/*Currently, kilometers availaible only for the BMW*/
			if(sourceEvent.getSourceId().equals("BMW"))
			{
				JSONObject row = new JSONObject(); 
				row.put("kilometers", Integer.parseInt(event.getValue()));
				row.put("date", event.getStartDateTime().toString()); 
				dataArray.put(row); 
			}
		}
		
		result.put("data", dataArray); 
		result.put("success", true);
		
		return result; 
	}
	

	
}
